package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "分类接口")
@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SetmealService setmealService;

    @ApiOperation("添加分类信息")
    @PostMapping
    public R save(@RequestBody Category category) {
        log.info("请求参数位：category = {}", category.toString());

        // 因为配置了自动填充公共数据，所以不需要手动填充了
        categoryService.save(category);
        return R.success();
    }

    @ApiOperation("分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "pageSize", value = "页面大小", dataTypeClass = Integer.class)
    })
    @GetMapping("/page")
    public R<Page<Category>> page(@RequestParam(required = false,defaultValue = "1") Integer page,
                                  @RequestParam(required = false,defaultValue = "10") Integer pageSize) {

        log.info("page = {}, pageSize = {}",page,pageSize);

        // 创建分页查询条件
        Page<Category> pageInfo = new Page<>(page, pageSize);

        // 创建条件查询/排序
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        categoryLambdaQueryWrapper.orderByAsc(Category::getSort);

        // 执行sql语句
        categoryService.page(pageInfo,categoryLambdaQueryWrapper);

        // 返回结果
        return R.success(pageInfo);

    }


    @ApiOperation("根据id删除分类信息")
    @ApiImplicitParam(name = "id", value = "分类id", dataTypeClass = Long.class)
    @DeleteMapping("/{id}")
    public R deleteById(@PathVariable Long id) {
        log.info("需要删除的id: {}", id);

        // 删除的业务逻辑复杂，需要扩展
        categoryService.remove(id);
        return R.success();

    }


    @ApiOperation("根据id查询信息")
    @ApiImplicitParam(name = "id", value = "分类id",dataTypeClass = Long.class)
    @GetMapping("/{id}")
    public R<Category> findById(@PathVariable Long id) {
        log.info("查询的id: {}",id);
        Category category = categoryService.getById(id);
        if (category != null) {
            return R.success(category);
        }
        return R.error("暂无数据!");
    }


    @ApiOperation("更新分类数据")
    @PutMapping
    public R modify(@RequestBody Category category) {
        log.info("修改的数据为：{}", category);
        boolean result = categoryService.updateById(category);
        if (result) {
            return R.success();
        }
        return R.error("修改数据失败！");
    }


    /**
     * 本项目是，根据菜品的分类查询数据
     * @param category
     * @return
     */
    @ApiOperation("根据菜品的分类查询数据")
    @GetMapping("/list")
    public R<List<Category>> selectCategory(Category category) {
        log.info("category = {}", category);

        // 判断查询数据的分类
        if (category.getType() == null) {
            // 查询所有的分类，表示移动端查询的数据
            // 1. 查询所有的分类
            List<Category> list = categoryService.list();
            // 2. 查询分类下商品的信息，根据状态查询
            // 3. 过滤掉，没有商品的分类
            List<Category> categoryList = list.stream().filter(category1 -> {
                // 过滤菜品中没有数据的分类
                if (category1.getType().equals(1)) {
                    LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    dishLambdaQueryWrapper.eq(Dish::getCategoryId, category1.getId());
                    dishLambdaQueryWrapper.eq(Dish::getStatus, 1);
                    List<Dish> dishList = dishService.list(dishLambdaQueryWrapper);

                    return dishList != null && dishList.size() != 0;
                } else {
                    LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId, category1.getId());
                    setmealLambdaQueryWrapper.eq(Setmeal::getStatus, 1);
                    List<Setmeal> setmealList = setmealService.list(setmealLambdaQueryWrapper);

                    return setmealList != null && setmealList.size() != 0;
                }
            }).collect(Collectors.toList());
            
            return R.success(categoryList);
        } else {
            // 服务端，获取具体分类的信息
            LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(Category::getType,category.getType());
            // 根据菜品的排序字段排序，如果排序字段一样，根据修改时间排序
            lambdaQueryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
            // 查询数据
            List<Category> list = categoryService.list(lambdaQueryWrapper);

            return R.success(list);
        }
    }

}
